<?php

namespace App\Http\Controllers\Admin\Wechat\Manager\Material;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Wechat\ImageGroup;
use App\Models\Wechat\Image as WechatImage;
use DB;

class ImageGroupController extends AdminController
{
    /**
	 * 获取所有图片分组
	 * @return [type] [description]
	 */
    public function getGroups(){
    	$list = ImageGroup::orderBy('isDefault','desc')->get()->toArray();
    	array_unshift($list,
    		['id'=>-1,'name'=>'全部图片','isDefault'=>1,'total'=>WechatImage::count()],
    		['id'=>0,'name'=>'未分组','isDefault'=>1,'total'=>WechatImage::where(['wechat_image_group_id'=>0])->count()]
    	);
    	$this->ajaxJson(0,'',$list);
    }

    /**
     * 获取所有分组
     * @return [type] [description]
     */
    public function getAllSingle(){
        $this->ajaxJson(0,'',ImageGroup::orderBy('isDefault','desc')->get());
    }

    /**
     * 验证分组名重名
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function checkGroup(Request $request){
    	$result = $this->_check_unique_name($request->input('name'),$request->input('id'));
    	$this->ajaxJson(0,'',['result'=>$result]);
    }

    /**
     * 更新分组名
     * @return [type] [description]
     */
    public function updateOne(Request $request){
    	$id = $request->input('id');
    	if($id){
    		$imageGroup = $this->_get_one($id);
    	}else{
    		$imageGroup = new ImageGroup();
    	}
    	$imageGroup->name = $request->input('name');
    	$imageGroup->save();
    	$this->ajaxJson(0,'更新成功');
    }

    public function deleteGroup($id){
        $this->_get_one($id);

        try {
            DB::beginTransaction();
            DB::table('wechat_image')->where('wechat_image_group_id',$id)->update(['wechat_image_group_id'=>0]);
            DB::table('wechat_image_group')->where('id',$id)->delete();
            DB::commit();
            $this->ajaxJson(0,'删除成功');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'删除失败');
        }
    }

    /**
     * 公共验证分组名重名
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    private function _check_unique_name($name,$id){
    	$where = ['name'=>$name];
    	return  ImageGroup::where($where)->where('id','!=',$id)->count() >0 ? false : true;
    }

    private function _get_one($id){
    	$imageGroup = ImageGroup::find($id);
    	if(!$imageGroup){
    		$this->ajaxJson(1,'分组不存在');
    	}
    	return $imageGroup;
    }
}
